﻿using WebSelfHost.Entity.Sys;
using WebSelfHost.Logic.Base;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using WebSelfHost.Utility.Operator;
using WebSelfHost.Utility.Core;

namespace WebSelfHost.Logic.Sys
{

    /// <summary>
    /// 权限信息表数据访问
    /// </summary>
    public class SysPermissionLogic : BaseLogic
    {

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool ActionValidate(string userId, string action)
        {
            var authorizeModules = GetList(userId);
            foreach (var item in authorizeModules)
            {
                if (!string.IsNullOrEmpty(item.Url))
                {
                    string[] url = item.Url.Split('?');
                    if (url[0].ToLower() == action.ToLower())
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 获得用户所有权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<SysPermission> GetList(string userId)
        {
            using (var db = GetInstance())
            {
                return
                    db.Queryable<SysUserRoleRelation, SysRoleAuthorize, SysPermission>((A, B, C) => new object[] {
                      JoinType.Left,A.RoleId == B.RoleId,
                      JoinType.Left,C.Id == B.ModuleId,
                    })
                    .Where((A, B, C) => A.UserId == userId && C.IsEnable == "1" && C.DeleteMark == "0")
                    .OrderBy((A, B, C) => C.SortCode)
                    .Select((A, B, C) => new SysPermission
                    {
                        Id = C.Id,
                        ParentId = C.ParentId,
                        Layer = C.Layer,
                        EnCode = C.EnCode,
                        Name = C.Name,
                        JsEvent = C.JsEvent,
                        Icon = C.Icon,
                        SymbolIndex = C.SymbolIndex,
                        Url = C.Url,
                        Remark = C.Remark,
                        Type = C.Type,
                        SortCode = C.SortCode,
                        IsPublic = C.IsPublic,
                        IsEnable = C.IsEnable,
                        IsEdit = C.IsEdit,
                        DeleteMark = C.DeleteMark,
                        CreateUser = C.CreateUser,
                        CreateTime = C.CreateTime,
                        ModifyUser = C.ModifyUser,
                        ModifyTime = C.ModifyTime
                    }).ToList();
            }
        }


        /// <summary>
        /// 获得所有权限信息分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyWord"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<SysPermission> GetList(int pageIndex, int pageSize, string keyWord, ref int totalCount)
        {
            using (var db = GetInstance())
            {
                if (keyWord.IsNullOrEmpty())
                {
                    return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0").OrderBy(it => it.SortCode).ToPageList(pageIndex, pageSize, ref totalCount);
                }
                return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0" && (it.Name.Contains(keyWord) || it.EnCode.Contains(keyWord))).OrderBy(it => it.SortCode).ToPageList(pageIndex, pageSize, ref totalCount);
            }
        }

        /// <summary>
        /// 删除权限信息
        /// </summary>
        /// <param name="primaryKeys"></param>
        /// <returns></returns>
        public int Delete(params string[] primaryKeys)
        {
            using (var db = GetInstance())
            {

                try
                {
                    db.BeginTran();
                    //删除权限与角色的对应关系。
                    List<string> list = db.Queryable<SysPermission>().In(primaryKeys).Select(it => it.Id).ToList();
                    db.Deleteable<SysPermission>().In(primaryKeys).ExecuteCommand();
                    db.Deleteable<SysRoleAuthorize>().Where(it => list.Contains(it.ModuleId)).ExecuteCommand();
                    db.CommitTran();
                    return 1;
                }
                catch (Exception ex)
                {
                    db.RollbackTran();
                    return 0;
                }
            }
        }


        /// <summary>
        /// 获得子节点
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public int GetChildCount(string parentId)
        {
            using (var db = GetInstance())
            {
                return db.Queryable<SysPermission>().Where(it => it.ParentId == parentId).ToList().Count();
            }
        }

        /// <summary>
        /// 获得所有权限信息
        /// </summary>
        /// <returns></returns>
        public List<SysPermission> GetList()
        {
            using (var db = GetInstance())
            {
                return db.Queryable<SysPermission>().Where(it => it.DeleteMark == "0").OrderBy(it => it.SortCode).ToList();
            }
        }


        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public SysPermission Get(string primaryKey)
        {
            using (var db = GetInstance())
            {
                return db.Queryable<SysPermission>().Where(it => it.Id == primaryKey).First();
            }
        }

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public int Insert(SysPermission model, string account)
        {
            using (var db = GetInstance())
            {
                model.Id = Guid.NewGuid().ToString().Replace("-", "");
                model.Layer = Get(model.ParentId).Layer += 1;
                model.IsEnable = model.IsEnable == null ? "0" : "1";
                model.IsEdit = model.IsEdit == null ? "0" : "1";
                model.IsPublic = model.IsPublic == null ? "0" : "1";
                model.DeleteMark = "0";
                model.CreateUser = account;
                model.CreateTime = DateTime.Now;
                model.ModifyUser = model.CreateUser;
                model.ModifyTime = model.CreateTime;
                return db.Insertable<SysPermission>(model).ExecuteCommand();
            }
        }

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        public int AppInsert(SysPermission model, string operateUser)
        {
            using (var db = GetInstance())
            {
                model.Id = Guid.NewGuid().ToString().Replace("-", "");
                model.Layer = Get(model.ParentId).Layer += 1;
                model.IsEnable =  "1";
                model.IsEdit =   "1";
                model.IsPublic =   "0";
                model.DeleteMark = "0";
                model.CreateUser = operateUser;
                model.CreateTime = DateTime.Now;
                model.ModifyUser = model.CreateUser;
                model.ModifyTime = model.CreateTime;
                return db.Insertable<SysPermission>(model).ExecuteCommand();
            }
        }


        /// <summary>
        /// 更新权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="operateUser"></param>
        /// <returns></returns>
        public int AppUpdate(SysPermission model, string operateUser)
        {
            using (var db = GetInstance())
            {
                model.Layer = Get(model.ParentId).Layer += 1;
                model.ModifyUser = operateUser;
                model.ModifyTime = DateTime.Now;
                return db.Updateable<SysPermission>(model).UpdateColumns(it => new
                {
                    it.ParentId,
                    it.Layer,
                    it.EnCode,
                    it.Name,
                    it.JsEvent,
                    it.Icon,
                    it.SymbolIndex,
                    it.Url,
                    it.Remark,
                    it.Type,
                    it.SortCode,
                    it.ModifyUser,
                    it.ModifyTime,
                }).ExecuteCommand();
            }
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        /// <param name="model"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        public int Update(SysPermission model, string account)
        {
            using (var db = GetInstance())
            {
                model.Layer = Get(model.ParentId).Layer += 1;
                model.IsEnable = model.IsEnable == null ? "0" : "1";
                model.IsEdit = model.IsEdit == null ? "0" : "1";
                model.IsPublic = model.IsPublic == null ? "0" : "1";
                model.ModifyUser =account;
                model.ModifyTime = DateTime.Now;
                return db.Updateable<SysPermission>(model).UpdateColumns(it => new
                {
                    it.ParentId,
                    it.Layer,
                    it.EnCode,
                    it.Name,
                    it.JsEvent,
                    it.Icon,
                    it.SymbolIndex,
                    it.Url,
                    it.Remark,
                    it.Type,
                    it.SortCode,
                    it.IsPublic,
                    it.IsEnable,
                    it.IsEdit,
                    it.ModifyUser,
                    it.ModifyTime,
                }).ExecuteCommand();
            }
        }
    }
}
